import { Base64 } from 'js-base64'
import { handleLogin, getUserInfo, doLoginByMobileOfClient } from '@/api/login'
import { setToken, getToken, setCookieToken } from '@/utils/auth'

// 重置user
const getDefaultState = () => {
  return {
    token: '',
    userInfo: ''
  }
}

const state = {
  token: JSON.parse(getToken()),
  userInfo: JSON.parse(localStorage.getItem('aimeet-userInfo'))
}

const mutations = {
  SET_TOKEN(state, payload) {
    state.token = payload
  },
  SET_USER_INFO(state, payload) {
    state.userInfo = payload
  },
  RESET_STATE(state) {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  // 短信登录
  loginSms({ commit, dispatch }, form) {
    return new Promise((resolve, reject) => {
      doLoginByMobileOfClient(
        {
          mobile: form.mobile,
          smsCode: form.smsCode
        }
      ).then(async(res) => {
        if (res.code === 200) {
          //  共享token
          await setCookieToken(res.data.tokenValue)

          await setToken(JSON.stringify({
            content: res.data.tokenValue,
            dataType: 'string',
            datetime: new Date().getTime()
          }))
          await commit('SET_TOKEN',
            {
              content: res.data.tokenValue,
              dataType: 'string',
              datetime: new Date().getTime()
            })
          dispatch('getUserInfo')
          resolve(res.data)
        }
      }).catch((e) => {
        reject(e)
      })
    })
  },
  // 普通登录
  login({ commit, dispatch }, form) {
    return new Promise((resolve, reject) => {
      handleLogin(
        {
          account: form.account,
          password: Base64.encode(form.password)
        }
      ).then(async r => {
        if (r.code === 200) {
          //  共享token
          await setCookieToken(r.data.tokenValue)

          await setToken(JSON.stringify({
            content: r.data.tokenValue,
            dataType: 'string',
            datetime: new Date().getTime()
          }))
          await commit('SET_TOKEN',
            {
              content: r.data.tokenValue,
              dataType: 'string',
              datetime: new Date().getTime()
            })
          dispatch('getUserInfo')
          resolve(r.data)
        }
      }).catch((e) => {
        reject(e)
      })
    })
  },
  // 基本信息
  async getUserInfo({ commit }) {
    const res = await getUserInfo()
    if (res.code === 200) {
      commit('SET_USER_INFO', {
        content: res.data,
        dateType: 'object',
        datetime: new Date().getTime()
      })
      localStorage.setItem('aimeet-userInfo', JSON.stringify({
        content: res.data,
        dateType: 'object',
        datetime: new Date().getTime()
      }))
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
